package pri.damai.xiaowu.anydoor.netty.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import pri.damai.xiaowu.anydoor.netty.ChannelStore;

import java.util.Map;

/**
 * 健壮性处理器
 * @Desc 在此处理客户端掉线等意外问题。
 * @Author yxf
 * @Date 2022/7/27 21:36
 * 但行好事，莫问前程。
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class RobustHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Map<Channel,Integer> channelIntegerMap = ChannelStore.CHANNEL_USER_MAP;
        Integer userId = channelIntegerMap.get(ctx.channel());
        Map<Integer, Channel> userChannelMap = ChannelStore.USER_CHANNEL_MAP;
        userChannelMap.remove(userId);
        channelIntegerMap.remove(ctx.channel());
        log.info("用户"+ userId +"掉线。");
    }
}
